package com.lanvideo.controller;

import com.lanvideo.entity.Question;
import com.lanvideo.service.QuestionService;
import com.lanvideo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题目管理控制器
 */
@RestController
@RequestMapping("/api/question")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private UserService userService;

    /**
     * 获取题目列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getQuestionList(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看题目列表");
                return ResponseEntity.ok(result);
            }
            
            List<Question> questions = questionService.getAllQuestions();
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 创建题目
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createQuestion(@RequestBody Question question, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以创建题目");
                return ResponseEntity.ok(result);
            }
            
            if (questionService.createQuestion(question)) {
                result.put("success", true);
                result.put("message", "题目创建成功");
            } else {
                result.put("success", false);
                result.put("message", "题目创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 更新题目
     */
    @PutMapping("/update/{questionId}")
    public ResponseEntity<Map<String, Object>> updateQuestion(@PathVariable Integer questionId, 
                                                            @RequestBody Question question, 
                                                            HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以更新题目");
                return ResponseEntity.ok(result);
            }
            
            question.setId(questionId);
            if (questionService.updateQuestion(question)) {
                result.put("success", true);
                result.put("message", "题目更新成功");
            } else {
                result.put("success", false);
                result.put("message", "题目更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 删除题目
     */
    @DeleteMapping("/delete/{questionId}")
    public ResponseEntity<Map<String, Object>> deleteQuestion(@PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以删除题目");
                return ResponseEntity.ok(result);
            }
            
            if (questionService.deleteQuestion(questionId)) {
                result.put("success", true);
                result.put("message", "题目删除成功");
            } else {
                result.put("success", false);
                result.put("message", "题目删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID获取题目
     */
    @GetMapping("/{questionId}")
    public ResponseEntity<Map<String, Object>> getQuestionById(@PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看题目详情");
                return ResponseEntity.ok(result);
            }
            
            Question question = questionService.getQuestionById(questionId);
            if (question != null) {
                result.put("success", true);
                result.put("question", question);
            } else {
                result.put("success", false);
                result.put("message", "题目不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 获取所有分类
     */
    @GetMapping("/categories")
    public ResponseEntity<Map<String, Object>> getAllCategories(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以查看分类");
                return ResponseEntity.ok(result);
            }
            
            List<String> categories = questionService.getAllCategories();
            result.put("success", true);
            result.put("categories", categories);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 搜索题目
     */
    @GetMapping("/search")
    public ResponseEntity<Map<String, Object>> searchQuestions(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) Integer difficulty,
            HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer userId = (Integer) session.getAttribute("userId");
            if (userId == null || userService.getUserById(userId).getRole() != 1) {
                result.put("success", false);
                result.put("message", "只有老师可以搜索题目");
                return ResponseEntity.ok(result);
            }
            
            List<Question> questions = questionService.searchQuestions(keyword, category, difficulty, userId);
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员获取所有题目列表
     */
    @GetMapping("/admin/all")
    public ResponseEntity<Map<String, Object>> getAllQuestionsForAdmin(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以查看所有题目");
                return ResponseEntity.ok(result);
            }
            
            List<Question> questions = questionService.getAllQuestionsForAdmin();
            result.put("success", true);
            result.put("questions", questions);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员创建题目
     */
    @PostMapping("/admin/create")
    public ResponseEntity<Map<String, Object>> createQuestionByAdmin(@RequestBody Question question, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以创建题目");
                return ResponseEntity.ok(result);
            }
            
            // 设置创建者为当前管理员
            question.setTeacherId(adminId);
            boolean success = questionService.createQuestion(question);
            if (success) {
                result.put("success", true);
                result.put("message", "题目创建成功");
            } else {
                result.put("success", false);
                result.put("message", "题目创建失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员更新题目
     */
    @PutMapping("/admin/update/{questionId}")
    public ResponseEntity<Map<String, Object>> updateQuestionByAdmin(@PathVariable Integer questionId, 
                                                                    @RequestBody Question question, 
                                                                    HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以更新题目");
                return ResponseEntity.ok(result);
            }
            
            question.setId(questionId);
            boolean success = questionService.updateQuestion(question);
            if (success) {
                result.put("success", true);
                result.put("message", "题目更新成功");
            } else {
                result.put("success", false);
                result.put("message", "题目更新失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 管理员删除题目
     */
    @DeleteMapping("/admin/delete/{questionId}")
    public ResponseEntity<Map<String, Object>> deleteQuestionByAdmin(@PathVariable Integer questionId, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer adminId = (Integer) session.getAttribute("userId");
            if (adminId == null || userService.getUserById(adminId).getRole() != 0) {
                result.put("success", false);
                result.put("message", "只有管理员可以删除题目");
                return ResponseEntity.ok(result);
            }
            
            boolean success = questionService.deleteQuestion(questionId);
            if (success) {
                result.put("success", true);
                result.put("message", "题目删除成功");
            } else {
                result.put("success", false);
                result.put("message", "题目删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "系统错误：" + e.getMessage());
        }
        return ResponseEntity.ok(result);
    }
}
